package com.qys.livesMall.app.user.service.impl;


import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qys.livesMall.app.user.mapper.H2AppUserMapper;
import com.qys.livesMall.app.user.model.dto.sys.HandselQueryDTO;
import com.qys.livesMall.app.user.model.entity.H2AppUser;
import com.qys.livesMall.app.user.model.vo.PlatformBalanceDetailVO;
import com.qys.livesMall.app.user.model.vo.UserAccountDetailVO;
import com.qys.livesMall.app.user.model.vo.UserBalanceDetailVO;
import com.qys.livesMall.app.user.model.vo.sys.HandselVO;
import com.qys.livesMall.app.user.model.vo.sys.ProfitAndLossStatisticsVO;
import com.qys.livesMall.app.user.service.IH2AppUserBalanceLogService;
import com.qys.livesMall.app.user.service.IH2AppUserService;
import com.qys.livesMall.common.exception.enums.ExceptionEnum;
import com.qys.livesMall.common.message.MessageServer;
import com.qys.livesMall.common.utils.bean.BeanProUtils;
import com.qys.livesMall.finance.enums.AccountBusinessTypeEnum;
import com.qys.livesMall.finance.enums.FinanceMessageEnum;
import com.qys.livesMall.finance.model.dto.AccountDdetailSearch;
import com.qys.livesMall.finance.model.dto.AccountDetailSearch;
import com.qys.livesMall.finance.model.entity.FinanceAccountDetail;
import com.qys.livesMall.finance.model.entity.user.FinanceUserAccountDetail;
import com.qys.livesMall.finance.service.FinanceAccountDetailService;
import com.qys.livesMall.finance.service.FinanceUserAccountDetailService;
import com.qys.livesMall.framework.view.BaseQuery;
import com.qys.livesMall.framework.view.QysPage;
import com.qys.livesMall.system.source.domain.vo.dict.DictVO;
import com.qys.livesMall.system.source.service.ISysDictTypeService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户资金变动记录 服务实现类
 * </p>
 *
 * @author dp
 * @since 2023-04-24
 */
@Service
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class H2AppUserBalanceLogServiceImpl implements IH2AppUserBalanceLogService {

    private final FinanceUserAccountDetailService financeUserAccountDetailService;
    private final IH2AppUserService appUserService;
    private final FinanceAccountDetailService financeAccountDetailService;
    private final ISysDictTypeService dictDataService;
    private final MessageServer messageServer;
    private final H2AppUserMapper appUserMapper;

    public QysPage<UserAccountDetailVO> page(AccountDdetailSearch search) {
        List<H2AppUser> users=null;
        if (StringUtils.isNotBlank(search.getUserName())){
            users=appUserService.getbyUserNameLike(search.getUserName(),search.getUserType());
            if (!CollectionUtils.isEmpty(users)){
                search.setUserIds(users.stream().map(H2AppUser::getId).collect(Collectors.toList()).stream().map(Long::valueOf).collect(Collectors.toList()));
            }else {
                search.setUserIds(Arrays.asList(-1L));
            }
        }
        QysPage<FinanceUserAccountDetail> page=financeUserAccountDetailService.listPage(search);
        if (CollectionUtils.isEmpty(page.getRecords())){
            return QysPage.build(search);
        }
        if (CollectionUtils.isEmpty(users)){
            List<Long> userIds = page.getRecords().stream().map(FinanceUserAccountDetail::getUserId).collect(Collectors.toList());
            users = appUserService.listByIds(userIds);
        }
        Map<String, H2AppUser> userMap = users.stream().collect(Collectors.toMap(H2AppUser::getId, v -> v));
        List<UserAccountDetailVO> vos=new ArrayList<>();
        page.getRecords().forEach(e->{
            UserAccountDetailVO vo= BeanProUtils.copyProperties(e, UserAccountDetailVO::new);
            vo.setPayDate(e.getPayDate().atZone(ZoneId.systemDefault()).toEpochSecond());
            H2AppUser user=userMap.get(String.valueOf(e.getUserId()));
            if (null != user){
                vo.setUserName(user.getUserName());
                vo.setNickName(user.getNickName());
                vo.setUserRandomId(user.getUserRandomId());
            }
            vos.add(vo);
        });
        return QysPage.build(search).setRecords(vos).setTotal(page.getTotal());
    }

    @Override
    public QysPage<PlatformBalanceDetailVO> platformList(AccountDetailSearch search) {
        QysPage<FinanceAccountDetail> page=financeAccountDetailService.list(search);
        if (CollectionUtils.isEmpty(page.getRecords())){
            return QysPage.build(search);
        }        List<PlatformBalanceDetailVO> vos= BeanProUtils.copyListProperties(page.getRecords(),PlatformBalanceDetailVO::new);
        return QysPage.build(search).setRecords(vos).setTotal(page.getTotal());

    }

    @Override
    public QysPage<UserBalanceDetailVO> pageByApp(AccountDetailSearch search,String languageType) {
        QysPage<FinanceUserAccountDetail> page=financeUserAccountDetailService.list(search);
        if (CollectionUtils.isEmpty(page.getRecords())){
            return QysPage.build(search);
        }
        List<UserBalanceDetailVO> vos= BeanProUtils.copyListProperties(page.getRecords(),UserBalanceDetailVO::new);
        //
        List<DictVO> bus_typeVOS=dictDataService.selectDictDataByType("bus_type",languageType);
        Map<String,String> busMap=bus_typeVOS.stream().collect(Collectors.toMap(DictVO::getDictValue,DictVO::getDictLabel));
        List<DictVO> bus_type_detailVOS=dictDataService.selectDictDataByType("bus_type_detail",languageType);
        Map<String,String> busDetailMap=bus_type_detailVOS.stream().collect(Collectors.toMap(DictVO::getDictValue,DictVO::getDictLabel));
        vos.stream().forEach(vo->{
            vo.setCounterparty(messageServer.getMsg(ExceptionEnum.PLATFORM));
            vo.setStatus("success");
            if (Objects.equals(vo.getCode(),AccountBusinessTypeEnum.RECHARGE_CANCEL.getCode())||Objects.equals(vo.getCode(),AccountBusinessTypeEnum.WITHDRAWAL_CANCEL.getCode())){
                vo.setStatus("reject");
            }
            vo.setProductDesc(messageServer.getMsg(FinanceMessageEnum.getEnum(vo.getCode())));
            if (Objects.equals(vo.getCategory(),AccountBusinessTypeEnum.USER_ORDER.getType())){
                //查询订单和店铺
                Map<String,String> order= appUserMapper.getShopOrderInfo(vo.getBusinessNo());
                if(order==null){
                    order=new HashMap<>();
                }
                if (Objects.equals(vo.getCode(),AccountBusinessTypeEnum.USER_ORDER.getCode())){
                    vo.setCounterparty(order.get("shopName"));
                }
                vo.setProductDesc(order.get("name"));
                if (vo.getProductDesc()!=null) {
                    vo.setProductDesc(vo.getProductDesc()+"...");
                }
            }
            if (vo.getCode().equals(AccountBusinessTypeEnum.USER_ORDER.getCode())){
                List<String> list=financeUserAccountDetailService.getOrderSkuNameByOrderNo(vo.getBusinessNo());
                vo.setProductDesc(String.join(",", list));
            }
            vo.setCategory(busMap.get(vo.getCategory()));
            vo.setCode(busDetailMap.get(vo.getCode()));
            JSONObject o=JSONObject.parseObject(vo.getPayAfter());
            vo.setPayAfter(String.valueOf(o.get("totalBalance")));
            vo.setIcon(AccountBusinessTypeEnum.getIcon(vo.getCode()).getUrl());

        });
        return QysPage.build(search).setRecords(vos).setTotal(page.getTotal());
    }
    @Override
    public Page<HandselVO> handsel(HandselQueryDTO dto) {
        Page<HandselVO> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        page.setRecords(appUserMapper.getUserHandsel(page, dto)).convert(e->{
            FinanceUserAccountDetail lastUserHandsel = appUserMapper.getLastUserHandsel(e.getUserId());
            e.setAmountIncurred(lastUserHandsel.getAmountIncurred());
            e.setPayDate(lastUserHandsel.getPayDate());
            return e;
        });
        return page;
    }

    @Override
    public Page<ProfitAndLossStatisticsVO> profitAndLossStatistics(BaseQuery query) {
        Page<ProfitAndLossStatisticsVO> page = new Page<>(query.getPageNum(), query.getPageSize());
        page.setRecords(appUserMapper.profitAndLossStatistics(page));
        return page;
    }

}
